﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.UI.Common;
using Sinacor.OMM.HealthMonitor.Client;
using Sinacor.UI.Bovespa.Monitoracao.Model;
using Sinacor.OMM.HealthMonitor.Entity.HftProcessor;

namespace Sinacor.UI.Bovespa.Monitoracao.Presenter
{
    public class STMMonitor : BasePresenter<ISTMMonitor>
    {
        Communication.Configuracao _communicationConfiguracao = null;
        HealthMonitorClient _healthMonitorClient;
        EntityMonitor _entityMonitor;
        List<string> _hftKeysProcessors;
        List<Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData> _hftProcessors;
        public Int32 NumberOfHftProcessActived = 0;
        public int HftServerNumber = 0;
        const int KBYTE = 1024;
        const int MEGABYTE = 1024 * 1024;
        const int GIGABYTE = 1024 * 1024 * 1024;
        const int SECONDS = 1000;
        const int MINUTES = 60 * SECONDS;
        const int HOURS = 60 * MINUTES;
        const int DAYS = 24 * HOURS;

        public STMMonitor(ISTMMonitor view)
            : base(view)
        {
            _communicationConfiguracao = new Sinacor.UI.Bovespa.Monitoracao.Communication.Configuracao(this.Session);
            _entityMonitor = new EntityMonitor();
            _hftKeysProcessors = new List<string>();
            _hftProcessors = new List<Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData>();
        }

        public EntityMonitor entityMonitor
        {
            get { return _entityMonitor; }
        }

        public string KeepAlive
        {
            get { return " "; }
        }

        public bool GlobalHftStatus
        {
            get { return CheckHftProcessesOk(_hftProcessors); }
        }

        public bool STMConectionReceptorOk
        {
            get { return entityMonitor.ReceptorMonitor.Connected == entityMonitor.ReceptorMonitor.GoodStateConnected; }
        }

        public bool ReceptorAverageTimeToSendAckOk
        {
            get { return entityMonitor.ReceptorMonitor.AverageTimeToSendAckTimeSpan <= entityMonitor.ReceptorMonitor.LimitAverageTimeToSendAck; }
        }

        public bool ReceptorInternalQueuedOk
        {
            get { return entityMonitor.ReceptorMonitor.ReceiverStoppedByQueueLimitReached == entityMonitor.ReceptorMonitor.GoodStateReceiverStoppedByQueueLimitReached; }
        }

        public bool ReceptorTotalInternalQueuedMessagesOk
        {
            get { return entityMonitor.ReceptorMonitor.InternalQueuedMessages_01_Quantity <= entityMonitor.ReceptorMonitor.TotalInternalQueuedMessages; }
        }

        public bool ReceptorPrivateMemoryOk
        {
            get { return entityMonitor.ReceptorMonitor.PrivateMemoryBytes <= entityMonitor.ReceptorMonitor.LimitPrivateMemory; }
        }

        public bool ReceptorHandleCountOk
        {
            get { return entityMonitor.ReceptorMonitor.HandleCount <= entityMonitor.ReceptorMonitor.LimitHandleCount; }
        }

        public bool ReceptorThreadCountOk
        {
            get { return entityMonitor.ReceptorMonitor.ThreadCount <= entityMonitor.ReceptorMonitor.LimitThreadCount; }
        }

        public bool RouterInternalQueue1Ok
        {
            get { return entityMonitor.RouterMonitor.InternalQueuedMessages_01_Quantity <= entityMonitor.RouterMonitor.LimitInternalQueuedMessages_01_Quantity; }
        }

        public bool RouterInternalQueue2Ok
        {
            get { return entityMonitor.RouterMonitor.InternalQueuedMessages_02_Quantity <= entityMonitor.RouterMonitor.LimitInternalQueuedMessages_02_Quantity; }
        }

        public bool RouterDataBaseQueueOk
        {
            get { return entityMonitor.RouterMonitor.MessagesDataBaseQueueQuantity <= entityMonitor.RouterMonitor.LimitMessagesDataBaseQueueQuantity; }
        }

        public bool RouterInsertDataBaseMessagesOk
        {
            get { return entityMonitor.RouterMonitor.DataBaseInsertAverageTime <= entityMonitor.RouterMonitor.LimitDataBaseInsertAverageTime; }
        }

        public bool RouterMessagesOk
        {
            get { return !entityMonitor.RouterMonitor.LimitStopedBySomeQueueExceedsLimit; }
        }

        public bool RouterPrivateMemoryOk
        {
            get { return entityMonitor.RouterMonitor.PrivateMemoryBytes <= entityMonitor.RouterMonitor.LimitPrivateMemory; }
        }

        public bool RouterHandleCountOk
        {
            get { return entityMonitor.RouterMonitor.HandleCount <= entityMonitor.RouterMonitor.LimitHandleCount; }
        }

        public bool RouterThreadCountOk
        {
            get { return entityMonitor.RouterMonitor.ThreadCount <= entityMonitor.RouterMonitor.LimitThreadCount; }
        }

        public bool RouterQueueOk
        {
            get { return entityMonitor.RouterMonitor.MsmqMonitor.QueueAcessible == entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueAcessible; }
        }

        public bool RouterQueueMessageOk
        {
            get { return entityMonitor.RouterMonitor.MsmqMonitor.QueuedMessages <= entityMonitor.RouterMonitor.MsmqMonitor.LimitQueuedMessages; }
        }

        public bool RouterQueueSizeOk
        {
            get { return entityMonitor.RouterMonitor.MsmqMonitor.QueueBytesSizeBytes <= entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueBytesSizeBytes; }
        }

        public bool OrderExecutorProcedureTimeOk
        {
            get { return entityMonitor.OrderExecutor.ProcedureExecutionlongTime <= entityMonitor.OrderExecutor.LimitProcedureExecutionTime; }
        }

        public bool OrderFinancialExecutorProcedureTimeOk
        {
            get { return entityMonitor.FinancialExecutor.ProcedureExecutionlongTime <= entityMonitor.FinancialExecutor.LimitProcedureExecutionTime; }
        }

        public bool OrderBusinessExecutorProcedureTimeOk
        {
            get { return entityMonitor.BusinessExecutor.ProcedureExecutionlongTime <= entityMonitor.BusinessExecutor.LimitProcedureExecutionTime; }
        }

        public bool OrderMatchExecutorProcedureTimeOk
        {
            get { return entityMonitor.MatchExecutor.ProcedureExecutionlongTime <= entityMonitor.MatchExecutor.LimitProcedureExecutionTime; }
        }

        public bool DumperQueueOk
        {
            get { return entityMonitor.DumperMonitor.MsmqMonitor.QueueAcessible == entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueAcessible; }
        }

        public bool DumperMessageOk
        {
            get { return entityMonitor.DumperMonitor.MsmqMonitor.QueuedMessages <= entityMonitor.DumperMonitor.MsmqMonitor.LimitQueuedMessages; }
        }

        public bool DumperQueueSizeOk
        {
            get { return entityMonitor.DumperMonitor.MsmqMonitor.QueueBytesSizeBytes <= entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueBytesSizeBytes; }
        }

        public bool DumperHandleCountOk
        {
            get { return entityMonitor.DumperMonitor.HandleCount <= entityMonitor.DumperMonitor.LimitHandleCount; }
        }

        public List<Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData> HFTProcessList
        {
            get { return _hftProcessors; }
        }

        public HFTProcessMonitorEntity ItemHFTProcessMonitor { get; set; }

        public void InitializeMonitor()
        {
            Model.MonitorOMMConfiguracao _configMonitor = _communicationConfiguracao.ObterMonitorOMMConfiguracaoCliente();

            _healthMonitorClient = HealthMonitorClient.GetInstance(_configMonitor.TcpServerPort, _configMonitor.TcpServerHostName);
            _healthMonitorClient.OnHealthStatusEvent += new HealthMonitorClient.HealthStatusHandler(_healthMonitorClient_OnHealthStatusEvent);
            _healthMonitorClient.OnConnectEvent += new HealthMonitorClient.ConnectHandler(_healthMonitorClient_OnConnectEvent);
            _healthMonitorClient.OnDisconnectEvent += new HealthMonitorClient.DisconnectHandler(_healthMonitorClient_OnDisconnectEvent);
            _healthMonitorClient.Start();
        }

        void _healthMonitorClient_OnDisconnectEvent()
        {
            View.DisableScreen();
        }

        void _healthMonitorClient_OnConnectEvent()
        {
            View.EnableScreen();
        }

        void _healthMonitorClient_OnHealthStatusEvent(Sinacor.OMM.HealthMonitor.Entity.HealthData healthData)
        {
            View.KeepAlive();
            //Receptor Health Information
            if (healthData != null && healthData.ReceiverHealthStatus != null)
            {
                View.SetReceptorState(true);
                _entityMonitor.ReceptorMonitor.Connected = healthData.ReceiverHealthStatus.StmConnectionInfo.Connected;
                _entityMonitor.ReceptorMonitor.GoodStateConnected = healthData.ReceiverHealthStatus.StmConnectionInfo.GoodStateConnected;
                _entityMonitor.ReceptorMonitor.ErrorEventsQuantity = healthData.ReceiverHealthStatus.StmConnectionInfo.ErrorEventsQuantity;
                _entityMonitor.ReceptorMonitor.SuccessfulConnectionsQuantity = healthData.ReceiverHealthStatus.StmConnectionInfo.SuccessfulConnectionsQuantity;
                _entityMonitor.ReceptorMonitor.UnsuccessfulConnectionsQuantity = healthData.ReceiverHealthStatus.StmConnectionInfo.UnsuccessfulConnectionsQuantity;
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.StmConnectionInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToSendAck))
                    _entityMonitor.ReceptorMonitor.AverageTimeToSendAckTimeSpan = TimeSpan.Parse(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToSendAck);
                else
                    _entityMonitor.ReceptorMonitor.AverageTimeToSendAckTimeSpan = TimeSpan.MinValue;
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.StmConnectionInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToSendAck))
                    _entityMonitor.ReceptorMonitor.AverageTimeToSendAck = TimeAdjustment(TimeSpan.Parse(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToSendAck).TotalMilliseconds);
                else
                    _entityMonitor.ReceptorMonitor.AverageTimeToSendAck = TimeAdjustment(0);
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.StmConnectionInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.StmConnectionInfo.LimitAverageTimeToSendAck))
                    _entityMonitor.ReceptorMonitor.LimitAverageTimeToSendAck = TimeSpan.Parse(healthData.ReceiverHealthStatus.StmConnectionInfo.LimitAverageTimeToSendAck);
                else
                    _entityMonitor.ReceptorMonitor.LimitAverageTimeToSendAck = TimeSpan.MinValue;

                _entityMonitor.ReceptorMonitor.ReceivedMessagesForSecond = healthData.ReceiverHealthStatus.StatisticInfo.ReceivedMessagesForSecond;
                _entityMonitor.ReceptorMonitor.lReceivedMessagesQuantity = healthData.ReceiverHealthStatus.StatisticInfo.lReceivedMessagesQuantity;
                _entityMonitor.ReceptorMonitor.LastReceivedMessageTimeStamp = healthData.ReceiverHealthStatus.StatisticInfo.LastReceivedMessageTimeStamp.ToShortTimeString();
                _entityMonitor.ReceptorMonitor.LastReceivedMessageId = healthData.ReceiverHealthStatus.StatisticInfo.LastReceivedMessageId;
                _entityMonitor.ReceptorMonitor.InternalQueuedMessages_01_Quantity = healthData.ReceiverHealthStatus.StatisticInfo.InternalQueuedMessages_01_Quantity;
                _entityMonitor.ReceptorMonitor.TotalInternalQueuedMessages = healthData.ReceiverHealthStatus.StatisticInfo.TotalInternalQueuedMessages;

                _entityMonitor.ReceptorMonitor.ReceiverQueueConnectionsReTries = healthData.ReceiverHealthStatus.MsmqConnectionInfo.ReceiverQueueConnectionsReTries;
                _entityMonitor.ReceptorMonitor.DumpQueueConnectionsReTries = healthData.ReceiverHealthStatus.MsmqConnectionInfo.DumpQueueConnectionsReTries;
                _entityMonitor.ReceptorMonitor.ReceiverStoppedByQueueLimitReached = healthData.ReceiverHealthStatus.MsmqConnectionInfo.ReceiverStoppedByQueueLimitReached;
                _entityMonitor.ReceptorMonitor.GoodStateReceiverStoppedByQueueLimitReached = healthData.ReceiverHealthStatus.MsmqConnectionInfo.GoodStateReceiverStoppedByQueueLimitReached;

                _entityMonitor.ReceptorMonitor.LimitPrivateMemory = healthData.ReceiverHealthStatus.ProcessDataInfo.LimitPrivateMemory;
                _entityMonitor.ReceptorMonitor.LimitHandleCount = healthData.ReceiverHealthStatus.ProcessDataInfo.LimitHandleCount;
                _entityMonitor.ReceptorMonitor.LimitThreadCount = healthData.ReceiverHealthStatus.ProcessDataInfo.LimitThreadCount;
                _entityMonitor.ReceptorMonitor.PrivateMemory = SizeAdjustmentBytes(healthData.ReceiverHealthStatus.ProcessDataInfo.PrivateMemory);
                _entityMonitor.ReceptorMonitor.PrivateMemoryBytes = healthData.ReceiverHealthStatus.ProcessDataInfo.PrivateMemory;
                _entityMonitor.ReceptorMonitor.HandleCount = healthData.ReceiverHealthStatus.ProcessDataInfo.HandleCount;
                _entityMonitor.ReceptorMonitor.ThreadCount = healthData.ReceiverHealthStatus.ProcessDataInfo.ThreadCount;
                _entityMonitor.ReceptorMonitor.InitializedDate = healthData.ReceiverHealthStatus.ProcessDataInfo.InitializedDate;
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.ProcessDataInfo.UpTime))
                    _entityMonitor.ReceptorMonitor.UpTime = TimeSpan.Parse(healthData.ReceiverHealthStatus.ProcessDataInfo.UpTime);
                else
                    _entityMonitor.ReceptorMonitor.UpTime = TimeSpan.MinValue;
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.ProcessDataInfo.PrivilegedProcessorTime))
                    _entityMonitor.ReceptorMonitor.PrivilegedProcessorTime = TimeSpan.Parse(healthData.ReceiverHealthStatus.ProcessDataInfo.PrivilegedProcessorTime);
                else
                    _entityMonitor.ReceptorMonitor.PrivilegedProcessorTime = TimeSpan.MinValue;
                _entityMonitor.ReceptorMonitor.MachineIPAddress = healthData.ReceiverHealthStatus.ProcessDataInfo.MachineIPAddress;
                _entityMonitor.ReceptorMonitor.MachineName = healthData.ReceiverHealthStatus.ProcessDataInfo.MachineName;
                _entityMonitor.ReceptorMonitor.ErrorData.BusinessMessage = healthData.ReceiverHealthStatus.ErrorData.BusinessMessage;
                _entityMonitor.ReceptorMonitor.ErrorData.ErrorCode = healthData.ReceiverHealthStatus.ErrorData.ErrorCode;
                _entityMonitor.ReceptorMonitor.ErrorData.ErrorDescription = healthData.ReceiverHealthStatus.ErrorData.ErrorDescription;
                _entityMonitor.ReceptorMonitor.ErrorData.ExceptionMessage = healthData.ReceiverHealthStatus.ErrorData.ExceptionMessage;
                _entityMonitor.ReceptorMonitor.ErrorData.ProcedureToTake = healthData.ReceiverHealthStatus.ErrorData.ProcedureToTake;
                _entityMonitor.ReceptorMonitor.ErrorData.Source = healthData.ReceiverHealthStatus.ErrorData.Source;
                if (healthData.ReceiverHealthStatus != null && healthData.ReceiverHealthStatus.StmConnectionInfo != null && !String.IsNullOrEmpty(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToCallAck))
                    _entityMonitor.ReceptorMonitor.AverageTimeToCallAck = TimeAdjustment(TimeSpan.Parse(healthData.ReceiverHealthStatus.StmConnectionInfo.AverageTimeToCallAck).Milliseconds);
                else
                    _entityMonitor.ReceptorMonitor.AverageTimeToCallAck = TimeAdjustment(0);
            }
            else
            {
                _entityMonitor.ReceptorMonitor.ErrorData = new ErrorData();
                _entityMonitor.ReceptorMonitor.ErrorData.BusinessMessage = "Health Monitor recebeu a entidade Receptor nula, possivelmente o componente esta fora do ar.";
                _entityMonitor.ReceptorMonitor.ErrorData.ErrorCode = "ReceptorForaDoAr";
                _entityMonitor.ReceptorMonitor.ErrorData.ErrorDescription = "Receptor esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.ReceptorMonitor.ErrorData.ExceptionMessage = "Receptor esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.ReceptorMonitor.ErrorData.ProcedureToTake = "Verifique se o serviço do Receptor esta iniciado";
                _entityMonitor.ReceptorMonitor.ErrorData.Source = "Health Monitor";
                View.SetReceptorState(false);
            }

            //Router Health Information
            if (healthData != null && healthData.RouterHealthStatus != null)
            {
                View.SetRouterState(true);
                _entityMonitor.RouterMonitor.BlockProcessingAverageQuantity = healthData.RouterHealthStatus.DataBaseProcessInfo.BlockProcessingAverageQuantity;
                _entityMonitor.RouterMonitor.LimitDataBaseInsertAverageTime = healthData.RouterHealthStatus.DataBaseProcessInfo.LimitDataBaseInsertAverageTime;
                _entityMonitor.RouterMonitor.DataBaseInsertAverageTime = healthData.RouterHealthStatus.DataBaseProcessInfo.DataBaseInsertAverageTime;
                _entityMonitor.RouterMonitor.DataBaseSucessfulConnectionRetries = healthData.RouterHealthStatus.DataBaseProcessInfo.DataBaseSucessfulConnectionRetries;
                _entityMonitor.RouterMonitor.DataBaseUnsucessfulConnectionRetries = healthData.RouterHealthStatus.DataBaseProcessInfo.DataBaseUnsucessfulConnectionRetries;
                _entityMonitor.RouterMonitor.MessagesDataBaseQueueQuantity = healthData.RouterHealthStatus.DataBaseProcessInfo.MessagesDataBaseQueueQuantity;
                _entityMonitor.RouterMonitor.LimitMessagesDataBaseQueueQuantity = healthData.RouterHealthStatus.DataBaseProcessInfo.LimitMessagesDataBaseQueueQuantity;

                _entityMonitor.RouterMonitor.MsmqConnectionsRetries = healthData.RouterHealthStatus.MessageReceiverInfo.MsmqConnectionsRetries;
                _entityMonitor.RouterMonitor.TranslatedMessagesForSecond = healthData.RouterHealthStatus.MessageReceiverInfo.TranslatedMessagesForSecond;
                _entityMonitor.RouterMonitor.MessagesReceivedQuantity = healthData.RouterHealthStatus.MessageReceiverInfo.MessagesReceivedQuantity;
                _entityMonitor.RouterMonitor.InternalQueuedMessages_01_Quantity = healthData.RouterHealthStatus.MessageReceiverInfo.InternalQueuedMessages_01_Quantity;
                _entityMonitor.RouterMonitor.LimitInternalQueuedMessages_01_Quantity = healthData.RouterHealthStatus.MessageReceiverInfo.LimitInternalQueuedMessages_01_Quantity;

                _entityMonitor.RouterMonitor.RoutedMessagesForSecond = healthData.RouterHealthStatus.MessageRouterInfo.RoutedMessagesForSecond;
                _entityMonitor.RouterMonitor.DefaultFlowRoutedMessagesQuantity = healthData.RouterHealthStatus.MessageRouterInfo.DefaultFlowRoutedMessagesQuantity;
                _entityMonitor.RouterMonitor.OptimizedRoutedMessagesQuantity = healthData.RouterHealthStatus.MessageRouterInfo.OptimizedRoutedMessagesQuantity;
                _entityMonitor.RouterMonitor.HftRoutedMessagesQuantity = healthData.RouterHealthStatus.MessageRouterInfo.HftRoutedMessagesQuantity;
                _entityMonitor.RouterMonitor.TotalRoutedMessagesQuantity = healthData.RouterHealthStatus.MessageRouterInfo.TotalRoutedMessagesQuantity;
                _entityMonitor.RouterMonitor.MemoryControlledOrdersQuantity = healthData.RouterHealthStatus.MessageRouterInfo.MemoryControlledOrdersQuantity;
                _entityMonitor.RouterMonitor.InternalQueuedMessages_02_Quantity = healthData.RouterHealthStatus.MessageRouterInfo.InternalQueuedMessages_02_Quantity;
                _entityMonitor.RouterMonitor.LimitInternalQueuedMessages_02_Quantity = healthData.RouterHealthStatus.MessageRouterInfo.LimitInternalQueuedMessages_02_Quantity;

                _entityMonitor.RouterMonitor.StopedBySomeQueueExceedsLimit = healthData.RouterHealthStatus.StopedBySomeQueueExceedsLimit;
                _entityMonitor.RouterMonitor.LimitStopedBySomeQueueExceedsLimit = healthData.RouterHealthStatus.LimitStopedBySomeQueueExceedsLimit;

                _entityMonitor.RouterMonitor.LimitPrivateMemory = healthData.RouterHealthStatus.ProcessDataInfo.LimitPrivateMemory;
                _entityMonitor.RouterMonitor.LimitHandleCount = healthData.RouterHealthStatus.ProcessDataInfo.LimitHandleCount;
                _entityMonitor.RouterMonitor.LimitThreadCount = healthData.RouterHealthStatus.ProcessDataInfo.LimitThreadCount;
                if (healthData.RouterHealthStatus != null && healthData.RouterHealthStatus.ProcessDataInfo != null)
                    _entityMonitor.RouterMonitor.PrivateMemory = SizeAdjustmentBytes(healthData.RouterHealthStatus.ProcessDataInfo.PrivateMemory);
                else
                    _entityMonitor.RouterMonitor.PrivateMemory = SizeAdjustmentBytes(0);
                _entityMonitor.RouterMonitor.PrivateMemoryBytes = healthData.RouterHealthStatus.ProcessDataInfo.PrivateMemory;
                _entityMonitor.RouterMonitor.HandleCount = healthData.RouterHealthStatus.ProcessDataInfo.HandleCount;
                _entityMonitor.RouterMonitor.ThreadCount = healthData.RouterHealthStatus.ProcessDataInfo.ThreadCount;
                _entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueAcessible = healthData.RouterHealthStatus.MsmqRouter.LimitQueueAcessible ? "Sim" : "Não";
                _entityMonitor.RouterMonitor.MsmqMonitor.QueueAcessible = healthData.RouterHealthStatus.MsmqRouter.QueueAcessible ? "Sim" : "Não";
                _entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueBytesSizeBytes = healthData.RouterHealthStatus.MsmqRouter.LimitQueueBytesSize;
                if (healthData.RouterHealthStatus != null && healthData.RouterHealthStatus.MsmqRouter != null)
                    _entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(healthData.RouterHealthStatus.MsmqRouter.LimitQueueBytesSize);
                else
                    _entityMonitor.RouterMonitor.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(0);
                _entityMonitor.RouterMonitor.MsmqMonitor.LimitQueuedMessages = healthData.RouterHealthStatus.MsmqRouter.LimitQueuedMessages;
                _entityMonitor.RouterMonitor.MsmqMonitor.MessagesPerSecond = healthData.RouterHealthStatus.MsmqRouter.MessagesPerSecond;
                if (healthData.RouterHealthStatus != null && healthData.RouterHealthStatus.MsmqRouter != null)
                    _entityMonitor.RouterMonitor.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(healthData.RouterHealthStatus.MsmqRouter.QueueBytesSize);
                else
                    _entityMonitor.RouterMonitor.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(0);
                _entityMonitor.RouterMonitor.MsmqMonitor.QueueBytesSizeBytes = healthData.RouterHealthStatus.MsmqRouter.QueueBytesSize;
                _entityMonitor.RouterMonitor.MsmqMonitor.QueuedMessages = healthData.RouterHealthStatus.MsmqRouter.QueuedMessages;
                _entityMonitor.RouterMonitor.MsmqMonitor.QueuePath = healthData.RouterHealthStatus.MsmqRouter.QueuePath;

                _entityMonitor.RouterMonitor.InitializedDate = healthData.RouterHealthStatus.ProcessDataInfo.InitializedDate;
                if (healthData.RouterHealthStatus != null && healthData.RouterHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.RouterHealthStatus.ProcessDataInfo.UpTime))
                    _entityMonitor.RouterMonitor.UpTime = TimeSpan.Parse(healthData.RouterHealthStatus.ProcessDataInfo.UpTime);
                else
                    _entityMonitor.RouterMonitor.UpTime = TimeSpan.MinValue;
                if (healthData.RouterHealthStatus != null && healthData.RouterHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.RouterHealthStatus.ProcessDataInfo.PrivilegedProcessorTime))
                    _entityMonitor.RouterMonitor.PrivilegedProcessorTime = TimeSpan.Parse(healthData.RouterHealthStatus.ProcessDataInfo.PrivilegedProcessorTime);
                else
                    _entityMonitor.RouterMonitor.PrivilegedProcessorTime = TimeSpan.MinValue;
                _entityMonitor.RouterMonitor.MachineIPAddress = healthData.RouterHealthStatus.ProcessDataInfo.MachineIPAddress;
                _entityMonitor.RouterMonitor.MachineName = healthData.RouterHealthStatus.ProcessDataInfo.MachineName;
                _entityMonitor.RouterMonitor.ErrorData.BusinessMessage = healthData.RouterHealthStatus.ErrorData.BusinessMessage;
                _entityMonitor.RouterMonitor.ErrorData.ErrorCode = healthData.RouterHealthStatus.ErrorData.ErrorCode;
                _entityMonitor.RouterMonitor.ErrorData.ErrorDescription = healthData.RouterHealthStatus.ErrorData.ErrorDescription;
                _entityMonitor.RouterMonitor.ErrorData.ExceptionMessage = healthData.RouterHealthStatus.ErrorData.ExceptionMessage;
                _entityMonitor.RouterMonitor.ErrorData.ProcedureToTake = healthData.RouterHealthStatus.ErrorData.ProcedureToTake;
                _entityMonitor.RouterMonitor.ErrorData.Source = healthData.RouterHealthStatus.ErrorData.Source;
            }
            else
            {
                _entityMonitor.RouterMonitor.ErrorData = new ErrorData();
                _entityMonitor.RouterMonitor.ErrorData.BusinessMessage = "Health Monitor recebeu a entidade Router nula, possivelmente o componente esta fora do ar.";
                _entityMonitor.RouterMonitor.ErrorData.ErrorCode = "RoteadorForaDoAr";
                _entityMonitor.RouterMonitor.ErrorData.ErrorDescription = "Roteador esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.RouterMonitor.ErrorData.ExceptionMessage = "Roteador esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.RouterMonitor.ErrorData.ProcedureToTake = "Verifique se o serviço do Roteador esta iniciado";
                _entityMonitor.RouterMonitor.ErrorData.Source = "Health Monitor";
                View.SetRouterState(false);
            }

            //Dumper
            if (healthData != null && healthData.DumperHealthStatus != null)
            {
                View.SetDumperState(true);
                _entityMonitor.DumperMonitor.DumpRootPath = healthData.DumperHealthStatus.DumpRootPath;
                _entityMonitor.DumperMonitor.SavedMessagesPerSecond = healthData.DumperHealthStatus.SavedMessagesPerSecond;
                _entityMonitor.DumperMonitor.LimitPrivateMemory = healthData.DumperHealthStatus.ProcessDataInfo.LimitPrivateMemory;
                _entityMonitor.DumperMonitor.LimitHandleCount = healthData.DumperHealthStatus.ProcessDataInfo.LimitHandleCount;
                _entityMonitor.DumperMonitor.LimitThreadCount = healthData.DumperHealthStatus.ProcessDataInfo.LimitThreadCount;
                _entityMonitor.DumperMonitor.ProcessName = healthData.DumperHealthStatus.ProcessDataInfo.ProcessName;
                _entityMonitor.DumperMonitor.PrivateMemory = healthData.DumperHealthStatus.ProcessDataInfo.PrivateMemory;
                _entityMonitor.DumperMonitor.VirtualMemory = healthData.DumperHealthStatus.ProcessDataInfo.VirtualMemory;
                _entityMonitor.DumperMonitor.HandleCount = healthData.DumperHealthStatus.ProcessDataInfo.HandleCount;
                _entityMonitor.DumperMonitor.ThreadCount = healthData.DumperHealthStatus.ProcessDataInfo.ThreadCount;
                if (healthData.DumperHealthStatus != null && healthData.DumperHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.DumperHealthStatus.ProcessDataInfo.PrivilegedProcessorTime))
                    _entityMonitor.DumperMonitor.PrivilegedProcessorTime = TimeSpan.Parse(healthData.DumperHealthStatus.ProcessDataInfo.PrivilegedProcessorTime);
                else
                    _entityMonitor.DumperMonitor.PrivilegedProcessorTime = TimeSpan.MinValue;
                if (healthData.DumperHealthStatus != null && healthData.DumperHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.DumperHealthStatus.ProcessDataInfo.TotalProcessorTime))
                    _entityMonitor.DumperMonitor.TotalProcessorTime = TimeSpan.Parse(healthData.DumperHealthStatus.ProcessDataInfo.TotalProcessorTime);
                else
                    _entityMonitor.DumperMonitor.TotalProcessorTime = TimeSpan.MinValue;
                _entityMonitor.DumperMonitor.InitializedDate = healthData.DumperHealthStatus.ProcessDataInfo.InitializedDate;
                if (healthData.DumperHealthStatus != null && healthData.DumperHealthStatus.ProcessDataInfo != null && !String.IsNullOrEmpty(healthData.DumperHealthStatus.ProcessDataInfo.UpTime))
                    _entityMonitor.DumperMonitor.UpTime = TimeSpan.Parse(healthData.DumperHealthStatus.ProcessDataInfo.UpTime);
                else
                    _entityMonitor.DumperMonitor.UpTime = TimeSpan.MinValue;
                _entityMonitor.DumperMonitor.MachineName = healthData.DumperHealthStatus.ProcessDataInfo.MachineName;
                _entityMonitor.DumperMonitor.MachineIPAddress = healthData.DumperHealthStatus.ProcessDataInfo.MachineIPAddress;
                _entityMonitor.DumperMonitor.MachineMacAddress = healthData.DumperHealthStatus.ProcessDataInfo.MachineMacAddress;
                _entityMonitor.DumperMonitor.ProcessId = healthData.DumperHealthStatus.ProcessDataInfo.ProcessId;
                _entityMonitor.DumperMonitor.ThreadId = healthData.DumperHealthStatus.ProcessDataInfo.ThreadId;
                _entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueAcessible = healthData.DumperHealthStatus.MsmqDumper.LimitQueueAcessible ? "Sim" : "Não";
                _entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueBytesSizeBytes = healthData.DumperHealthStatus.MsmqDumper.LimitQueueBytesSize;
                if (healthData.DumperHealthStatus != null && healthData.DumperHealthStatus.MsmqDumper != null)
                    _entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(healthData.DumperHealthStatus.MsmqDumper.LimitQueueBytesSize);
                else
                    _entityMonitor.DumperMonitor.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(0);
                _entityMonitor.DumperMonitor.MsmqMonitor.LimitQueuedMessages = healthData.DumperHealthStatus.MsmqDumper.LimitQueuedMessages;
                _entityMonitor.DumperMonitor.MsmqMonitor.MessagesPerSecond = healthData.DumperHealthStatus.MsmqDumper.MessagesPerSecond;
                _entityMonitor.DumperMonitor.MsmqMonitor.QueueAcessible = healthData.DumperHealthStatus.MsmqDumper.QueueAcessible ? "Sim" : "Não";
                if (healthData.DumperHealthStatus != null && healthData.DumperHealthStatus.MsmqDumper != null)
                    _entityMonitor.DumperMonitor.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(healthData.DumperHealthStatus.MsmqDumper.QueueBytesSize);
                else
                    _entityMonitor.DumperMonitor.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(0);
                _entityMonitor.DumperMonitor.MsmqMonitor.QueueBytesSizeBytes = healthData.DumperHealthStatus.MsmqDumper.QueueBytesSize;
                _entityMonitor.DumperMonitor.MsmqMonitor.QueuedMessages = healthData.DumperHealthStatus.MsmqDumper.QueuedMessages;
                _entityMonitor.DumperMonitor.MsmqMonitor.QueuePath = healthData.DumperHealthStatus.MsmqDumper.QueuePath;
                _entityMonitor.DumperMonitor.ErrorData.BusinessMessage = healthData.DumperHealthStatus.ErrorData.BusinessMessage;
                _entityMonitor.DumperMonitor.ErrorData.ErrorCode = healthData.DumperHealthStatus.ErrorData.ErrorCode;
                _entityMonitor.DumperMonitor.ErrorData.ErrorDescription = healthData.DumperHealthStatus.ErrorData.ErrorDescription;
                _entityMonitor.DumperMonitor.ErrorData.ExceptionMessage = healthData.DumperHealthStatus.ErrorData.ExceptionMessage;
                _entityMonitor.DumperMonitor.ErrorData.ProcedureToTake = healthData.DumperHealthStatus.ErrorData.ProcedureToTake;
                _entityMonitor.DumperMonitor.ErrorData.Source = healthData.DumperHealthStatus.ErrorData.Source;
            }
            else
            {
                _entityMonitor.DumperMonitor.ErrorData = new ErrorData();
                _entityMonitor.DumperMonitor.ErrorData.BusinessMessage = "Health Monitor recebeu a entidade Dumper nula, possivelmente o componente esta fora do ar.";
                _entityMonitor.DumperMonitor.ErrorData.ErrorCode = "DumperForaDoAr";
                _entityMonitor.DumperMonitor.ErrorData.ErrorDescription = "Dumper esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.DumperMonitor.ErrorData.ExceptionMessage = "Dumper esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.DumperMonitor.ErrorData.ProcedureToTake = "Verifique se o serviço do Dumper esta iniciado";
                _entityMonitor.DumperMonitor.ErrorData.Source = "Health Monitor";
                View.SetDumperState(false);
            }

            //OrderExecutor
            if (healthData != null && healthData.OrderExecutorStatus != null)
            {
                View.SetOrderExecutorState(true);
                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.OrderExecutor != null && !String.IsNullOrEmpty(healthData.OrderExecutorStatus.OrderExecutor.NextScheduleProcedure))
                    _entityMonitor.OrderExecutor.NextScheduleProcedure = TimeSpanAdjustment(healthData.OrderExecutorStatus.OrderExecutor.NextScheduleProcedure);
                else
                    _entityMonitor.OrderExecutor.NextScheduleProcedure = TimeSpanAdjustment(TimeSpan.MinValue.ToString());
                _entityMonitor.OrderExecutor.NumberOfExceptionsDataBase = healthData.OrderExecutorStatus.OrderExecutor.NumberOfExceptionsDataBase;
                _entityMonitor.OrderExecutor.ProcedureExecutionlongTime = healthData.OrderExecutorStatus.OrderExecutor.ProcedureExecutionTime;
                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.OrderExecutor != null)
                    _entityMonitor.OrderExecutor.ProcedureExecutionTime = TimeAdjustment(healthData.OrderExecutorStatus.OrderExecutor.ProcedureExecutionTime);
                else
                    _entityMonitor.OrderExecutor.ProcedureExecutionTime = TimeAdjustment(0);
                _entityMonitor.OrderExecutor.LimitProcedureExecutionTime = healthData.OrderExecutorStatus.OrderExecutor.LimitProcedureExecutionTime;
                _entityMonitor.OrderExecutor.ErrorData.BusinessMessage = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.BusinessMessage;
                _entityMonitor.OrderExecutor.ErrorData.ErrorCode = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.ErrorCode;
                _entityMonitor.OrderExecutor.ErrorData.ErrorDescription = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.ErrorDescription;
                _entityMonitor.OrderExecutor.ErrorData.ExceptionMessage = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.ExceptionMessage;
                _entityMonitor.OrderExecutor.ErrorData.ProcedureToTake = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.ProcedureToTake;
                _entityMonitor.OrderExecutor.ErrorData.Source = healthData.OrderExecutorStatus.OrderExecutor.ErrorData.Source;

                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.BusinessExecutor != null && !String.IsNullOrEmpty(healthData.OrderExecutorStatus.BusinessExecutor.NextScheduleProcedure))
                    _entityMonitor.BusinessExecutor.NextScheduleProcedure = TimeSpanAdjustment(healthData.OrderExecutorStatus.BusinessExecutor.NextScheduleProcedure);
                else
                    _entityMonitor.BusinessExecutor.NextScheduleProcedure = TimeSpanAdjustment(TimeSpan.MinValue.ToString());
                _entityMonitor.BusinessExecutor.NumberOfExceptionsDataBase = healthData.OrderExecutorStatus.BusinessExecutor.NumberOfExceptionsDataBase;
                _entityMonitor.BusinessExecutor.ProcedureExecutionlongTime = healthData.OrderExecutorStatus.BusinessExecutor.ProcedureExecutionTime;
                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.BusinessExecutor != null)
                    _entityMonitor.BusinessExecutor.ProcedureExecutionTime = TimeAdjustment(healthData.OrderExecutorStatus.BusinessExecutor.ProcedureExecutionTime);
                else
                    _entityMonitor.BusinessExecutor.ProcedureExecutionTime = TimeAdjustment(0);
                _entityMonitor.BusinessExecutor.LimitProcedureExecutionTime = healthData.OrderExecutorStatus.BusinessExecutor.LimitProcedureExecutionTime;
                _entityMonitor.BusinessExecutor.ErrorData.BusinessMessage = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.BusinessMessage;
                _entityMonitor.BusinessExecutor.ErrorData.ErrorCode = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.ErrorCode;
                _entityMonitor.BusinessExecutor.ErrorData.ErrorDescription = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.ErrorDescription;
                _entityMonitor.BusinessExecutor.ErrorData.ExceptionMessage = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.ExceptionMessage;
                _entityMonitor.BusinessExecutor.ErrorData.ProcedureToTake = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.ProcedureToTake;
                _entityMonitor.BusinessExecutor.ErrorData.Source = healthData.OrderExecutorStatus.BusinessExecutor.ErrorData.Source;

                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.FinancialExecutor != null && !String.IsNullOrEmpty(healthData.OrderExecutorStatus.FinancialExecutor.NextScheduleProcedure))
                    _entityMonitor.FinancialExecutor.NextScheduleProcedure = TimeSpanAdjustment(healthData.OrderExecutorStatus.FinancialExecutor.NextScheduleProcedure);
                else
                    _entityMonitor.FinancialExecutor.NextScheduleProcedure = TimeSpanAdjustment(TimeSpan.MinValue.ToString());
                _entityMonitor.FinancialExecutor.NumberOfExceptionsDataBase = healthData.OrderExecutorStatus.FinancialExecutor.NumberOfExceptionsDataBase;
                _entityMonitor.FinancialExecutor.ProcedureExecutionlongTime = healthData.OrderExecutorStatus.FinancialExecutor.ProcedureExecutionTime;
                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.FinancialExecutor != null)
                    _entityMonitor.FinancialExecutor.ProcedureExecutionTime = TimeAdjustment(healthData.OrderExecutorStatus.FinancialExecutor.ProcedureExecutionTime);
                else
                    _entityMonitor.FinancialExecutor.ProcedureExecutionTime = TimeAdjustment(0);
                _entityMonitor.FinancialExecutor.LimitProcedureExecutionTime = healthData.OrderExecutorStatus.FinancialExecutor.LimitProcedureExecutionTime;
                _entityMonitor.FinancialExecutor.ErrorData.BusinessMessage = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.BusinessMessage;
                _entityMonitor.FinancialExecutor.ErrorData.ErrorCode = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.ErrorCode;
                _entityMonitor.FinancialExecutor.ErrorData.ErrorDescription = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.ErrorDescription;
                _entityMonitor.FinancialExecutor.ErrorData.ExceptionMessage = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.ExceptionMessage;
                _entityMonitor.FinancialExecutor.ErrorData.ProcedureToTake = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.ProcedureToTake;
                _entityMonitor.FinancialExecutor.ErrorData.Source = healthData.OrderExecutorStatus.FinancialExecutor.ErrorData.Source;

                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.MatchExecutor != null && !String.IsNullOrEmpty(healthData.OrderExecutorStatus.MatchExecutor.NextScheduleProcedure))
                    _entityMonitor.MatchExecutor.NextScheduleProcedure = TimeSpanAdjustment(healthData.OrderExecutorStatus.MatchExecutor.NextScheduleProcedure);
                else
                    _entityMonitor.MatchExecutor.NextScheduleProcedure = TimeSpanAdjustment(TimeSpan.MinValue.ToString());
                _entityMonitor.MatchExecutor.NumberOfExceptionsDataBase = healthData.OrderExecutorStatus.MatchExecutor.NumberOfExceptionsDataBase;
                _entityMonitor.MatchExecutor.ProcedureExecutionlongTime = healthData.OrderExecutorStatus.MatchExecutor.ProcedureExecutionTime;
                if (healthData.OrderExecutorStatus != null && healthData.OrderExecutorStatus.MatchExecutor != null)
                    _entityMonitor.MatchExecutor.ProcedureExecutionTime = TimeAdjustment(healthData.OrderExecutorStatus.MatchExecutor.ProcedureExecutionTime);
                else
                    _entityMonitor.MatchExecutor.ProcedureExecutionTime = TimeAdjustment(0);
                _entityMonitor.MatchExecutor.LimitProcedureExecutionTime = healthData.OrderExecutorStatus.MatchExecutor.LimitProcedureExecutionTime;
                _entityMonitor.MatchExecutor.ErrorData.BusinessMessage = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.BusinessMessage;
                _entityMonitor.MatchExecutor.ErrorData.ErrorCode = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.ErrorCode;
                _entityMonitor.MatchExecutor.ErrorData.ErrorDescription = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.ErrorDescription;
                _entityMonitor.MatchExecutor.ErrorData.ExceptionMessage = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.ExceptionMessage;
                _entityMonitor.MatchExecutor.ErrorData.ProcedureToTake = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.ProcedureToTake;
                _entityMonitor.MatchExecutor.ErrorData.Source = healthData.OrderExecutorStatus.MatchExecutor.ErrorData.Source;
            }
            else
            {
                _entityMonitor.OrderExecutor.ErrorData = new ErrorData();
                _entityMonitor.OrderExecutor.ErrorData.BusinessMessage = "Health Monitor recebeu a entidade OrderExecutor nula, possivelmente o componente esta fora do ar.";
                _entityMonitor.OrderExecutor.ErrorData.ErrorCode = "OrderExecutorForaDoAr";
                _entityMonitor.OrderExecutor.ErrorData.ErrorDescription = "Executor de Ordem esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.OrderExecutor.ErrorData.ExceptionMessage = "Executor de Ordem esta com problemas, por favor verifique se o serviço iniciado";
                _entityMonitor.OrderExecutor.ErrorData.ProcedureToTake = "Verifique se o serviço do Executor de Ordem esta iniciado";
                _entityMonitor.OrderExecutor.ErrorData.Source = "Health Monitor";
                View.SetOrderExecutorState(false);
            }
            _entityMonitor.HFTMonitors.Clear();
            _hftKeysProcessors.Clear();
            lock (healthData.HftProcessorHealthStatus)
            {
                //Tratamento de dados HFT recebidos pelo Health Monitor
                if (healthData != null && healthData.HftProcessorHealthStatus != null)
                {
                    //Tratamento HFTProcess
                    if (healthData.HftProcessorHealthStatus.Count > 0)
                    {
                        NumberOfHftProcessActived = healthData.HftProcessorHealthStatus.Count;
                        View.SetHFTProcessState(true);
                        foreach (String item in healthData.HftProcessorHealthStatus.Keys)
                        {
                            _hftKeysProcessors.Add(item);
                        }

                        foreach (String s in _hftKeysProcessors)
                        {
                            if (healthData.HftProcessorHealthStatus[s] != null)
                            {
                                _entityMonitor.NumberOfHftProcess = healthData.HftProcessorHealthStatus[s].NumberofHftProcess;
                                HFTProcessMonitorEntity item = new HFTProcessMonitorEntity();

                                item.MsmqMonitor.QueueAcessible = healthData.HftProcessorHealthStatus[s].Msmq.QueueAcessible ? "Sim" : "Não";
                                item.MsmqMonitor.LimitQueueAcessible = healthData.HftProcessorHealthStatus[s].Msmq.LimitQueueAcessible ? "Sim" : "Não";
                                item.MsmqMonitor.QueuedMessages = healthData.HftProcessorHealthStatus[s].Msmq.QueuedMessages;
                                item.MsmqMonitor.LimitQueuedMessages = healthData.HftProcessorHealthStatus[s].Msmq.LimitQueuedMessages;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].Msmq != null)
                                    item.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(healthData.HftProcessorHealthStatus[s].Msmq.QueueBytesSize);
                                else
                                    item.MsmqMonitor.QueueBytesSize = SizeAdjustmentBytes(0);
                                item.MsmqMonitor.QueueBytesSizeBytes = healthData.HftProcessorHealthStatus[s].Msmq.QueueBytesSize;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].Msmq != null)
                                    item.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(healthData.HftProcessorHealthStatus[s].Msmq.LimitQueueBytesSize, 1);
                                else
                                    item.MsmqMonitor.LimitQueueBytesSize = SizeAdjustmentBytes(0, 1);
                                item.MsmqMonitor.LimitQueueBytesSizeBytes = healthData.HftProcessorHealthStatus[s].Msmq.LimitQueueBytesSize;

                                item.TotalMessages = healthData.HftProcessorHealthStatus[s].MessageProcessor.TotalMessages;
                                item.LastMessageTimeDate = healthData.HftProcessorHealthStatus[s].MessageProcessor.LastMessageTime;
                                item.LastMessageTime = healthData.HftProcessorHealthStatus[s].MessageProcessor.LastMessageTime.ToShortTimeString();
                                item.MessagesPerSecond = healthData.HftProcessorHealthStatus[s].MessageProcessor.MessagesPerSecond;
                                item.WaitingOpenOrderAverageTime = healthData.HftProcessorHealthStatus[s].MessageProcessor.WaitingOpenOrderAverageTime;
                                item.LimitWaitingOpenOrderAverageTime = healthData.HftProcessorHealthStatus[s].MessageProcessor.LimitWaitingOpenOrderAverageTime;
                                item.LimitWaitingOpenOrderAverageTimeString = TimeAdjustment(Convert.ToDouble(healthData.HftProcessorHealthStatus[s].MessageProcessor.LimitWaitingOpenOrderAverageTime));
                                item.TotalMsmqConnectionRetries = healthData.HftProcessorHealthStatus[s].TotalMsmqConnectionRetries;

                                item.OperationAverageTime = healthData.HftProcessorHealthStatus[s].Database.OperationAverageTime;
                                item.LimitOperationAverageTime = healthData.HftProcessorHealthStatus[s].Database.LimitOperationAverageTime;
                                item.SuccessfulTriesConnection = healthData.HftProcessorHealthStatus[s].Database.SuccessfulTriesConnection;
                                item.UnsuccessfulTriesConnection = healthData.HftProcessorHealthStatus[s].Database.UnsuccessfulTriesConnection;

                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null)
                                    item.PrivateMemory = SizeAdjustmentBytes(healthData.HftProcessorHealthStatus[s].ProcessData.PrivateMemory);
                                else
                                    item.PrivateMemory = SizeAdjustmentBytes(0);
                                item.PrivateMemoryBytes = healthData.HftProcessorHealthStatus[s].ProcessData.PrivateMemory;
                                item.LimitPrivateMemoryBytes = healthData.HftProcessorHealthStatus[s].ProcessData.LimitPrivateMemory;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null)
                                    item.LimitPrivateMemory = SizeAdjustmentBytes(healthData.HftProcessorHealthStatus[s].ProcessData.LimitPrivateMemory);
                                else
                                    item.LimitPrivateMemory = SizeAdjustmentBytes(0);
                                item.HandleCount = healthData.HftProcessorHealthStatus[s].ProcessData.HandleCount;
                                item.LimitHandleCount = healthData.HftProcessorHealthStatus[s].ProcessData.LimitHandleCount;
                                item.ThreadCount = healthData.HftProcessorHealthStatus[s].ProcessData.ThreadCount;
                                item.LimitThreadCount = healthData.HftProcessorHealthStatus[s].ProcessData.LimitThreadCount;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null && !String.IsNullOrEmpty(healthData.HftProcessorHealthStatus[s].ProcessData.PrivilegedProcessorTime))
                                    item.PrivilegedProcessorTime = TimeAdjustment(TimeSpan.Parse(healthData.HftProcessorHealthStatus[s].ProcessData.PrivilegedProcessorTime).TotalMilliseconds);
                                else
                                    item.PrivilegedProcessorTime = TimeAdjustment(0);
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null && !String.IsNullOrEmpty(healthData.HftProcessorHealthStatus[s].ProcessData.PrivilegedProcessorTime))
                                    item.PrivilegedProcessorTimeTimeSpan = TimeSpan.Parse(healthData.HftProcessorHealthStatus[s].ProcessData.PrivilegedProcessorTime);
                                else
                                    item.PrivilegedProcessorTimeTimeSpan = TimeSpan.MinValue;
                                item.InitializedDate = healthData.HftProcessorHealthStatus[s].ProcessData.InitializedDate;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null && !String.IsNullOrEmpty(healthData.HftProcessorHealthStatus[s].ProcessData.UpTime))
                                    item.UpTimeTimeSpan = TimeSpan.Parse(healthData.HftProcessorHealthStatus[s].ProcessData.UpTime);
                                else
                                    item.UpTimeTimeSpan = TimeSpan.MinValue;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null && !String.IsNullOrEmpty(healthData.HftProcessorHealthStatus[s].ProcessData.UpTime))
                                    item.UpTime = TimeAdjustment(TimeSpan.Parse(healthData.HftProcessorHealthStatus[s].ProcessData.UpTime).TotalMilliseconds);
                                else
                                    item.UpTime = TimeAdjustment(0);
                                item.ProcessId = healthData.HftProcessorHealthStatus[s].ProcessData.ProcessId;
                                item.ThreadId = healthData.HftProcessorHealthStatus[s].ProcessData.ThreadId;

                                item.ProcessName = healthData.HftProcessorHealthStatus[s].ProcessData.ProcessName;
                                item.VirtualMemory = healthData.HftProcessorHealthStatus[s].ProcessData.VirtualMemory;
                                if (healthData.HftProcessorHealthStatus[s] != null && healthData.HftProcessorHealthStatus[s].ProcessData != null && !String.IsNullOrEmpty(healthData.HftProcessorHealthStatus[s].ProcessData.TotalProcessorTime))
                                    item.TotalProcessorTime = TimeSpan.Parse(healthData.HftProcessorHealthStatus[s].ProcessData.TotalProcessorTime);
                                else
                                    item.TotalProcessorTime = TimeSpan.MinValue;
                                item.MachineName = healthData.HftProcessorHealthStatus[s].ProcessData.MachineName;
                                item.MachineIPAddress = healthData.HftProcessorHealthStatus[s].ProcessData.MachineIPAddress;
                                item.MachineMacAddress = healthData.HftProcessorHealthStatus[s].ProcessData.MachineMacAddress;
                                item.ErrorData.BusinessMessage = healthData.HftProcessorHealthStatus[s].ErrorData.BusinessMessage;
                                item.ErrorData.ErrorCode = healthData.HftProcessorHealthStatus[s].ErrorData.ErrorCode;
                                item.ErrorData.ErrorDescription = healthData.HftProcessorHealthStatus[s].ErrorData.ErrorDescription;
                                item.ErrorData.ExceptionMessage = healthData.HftProcessorHealthStatus[s].ErrorData.ExceptionMessage;
                                item.ErrorData.ProcedureToTake = healthData.HftProcessorHealthStatus[s].ErrorData.ProcedureToTake;
                                item.ErrorData.Source = healthData.HftProcessorHealthStatus[s].ErrorData.Source;
                                foreach (DistributionRules rules in healthData.HftProcessorHealthStatus[s].DistributionRules)
                                {
                                    item.PortRange.Add(rules.RangePort);
                                    item.ClientRule.Add(rules.ClientId);
                                }
                                _entityMonitor.HFTMonitors.Add(item);
                            }
                        }
                        //_entityMonitor.HFTMonitors.Sort((x, y) => string.Compare(x.HftId, y.HftId));

                        for (int i = 0; i <= 7; i++)
                        {
                            if ((_entityMonitor.HFTMonitors.Count - 1) < i)
                            {
                                _entityMonitor.HFTMonitors.Add(null);
                            }
                        }
                        if (_entityMonitor.HFTMonitors.Count > 0)
                        {
                            TranslateListHftProcessor(_entityMonitor.HFTMonitors);
                        }
                        ItemHFTProcessMonitor = entityMonitor.HFTMonitors[HftServerNumber];
                    }
                    else
                    {
                        NumberOfHftProcessActived = 0;
                        for (int i = 0; i <= 7; i++)
                        {
                            _entityMonitor.HFTMonitors.Add(null);
                        }
                        TranslateListHftProcessor(_entityMonitor.HFTMonitors);
                        ItemHFTProcessMonitor = new HFTProcessMonitorEntity();
                        _entityMonitor.HFTMonitors[0] = new HFTProcessMonitorEntity();
                        _entityMonitor.HFTMonitors[0].ErrorData = new ErrorData();
                        _entityMonitor.HFTMonitors[0].ErrorData.BusinessMessage = "Health Monitor recebeu a entidade HFTProcess nula, possivelmente o componente esta fora do ar.";
                        _entityMonitor.HFTMonitors[0].ErrorData.ErrorCode = "HFTProcessForaDoAr";
                        _entityMonitor.HFTMonitors[0].ErrorData.ErrorDescription = "Processo HFT esta com problemas, por favor verifique se o serviço iniciado";
                        _entityMonitor.HFTMonitors[0].ErrorData.ExceptionMessage = "Processo HFT esta com problemas, por favor verifique se o serviço iniciado";
                        _entityMonitor.HFTMonitors[0].ErrorData.ProcedureToTake = "Verifique se o serviço do Processo HFT esta iniciado";
                        _entityMonitor.HFTMonitors[0].ErrorData.Source = "Health Monitor";
                        View.DisableHFTMonitor();
                        View.SetHFTProcessState(false);
                    }
                    View.RefreshMonitor();
                }
                else
                {
                    _entityMonitor.HFTMonitors[0].ErrorData = new ErrorData();
                    _entityMonitor.HFTMonitors[0].ErrorData.BusinessMessage = "Health Monitor recebeu a entidade HFTProcess nula, possivelmente o componente esta fora do ar.";
                    _entityMonitor.HFTMonitors[0].ErrorData.ErrorCode = "HFTProcessForaDoAr";
                    _entityMonitor.HFTMonitors[0].ErrorData.ErrorDescription = "Processo HFT esta com problemas, por favor verifique se o serviço iniciado";
                    _entityMonitor.HFTMonitors[0].ErrorData.ExceptionMessage = "Processo HFT esta com problemas, por favor verifique se o serviço iniciado";
                    _entityMonitor.HFTMonitors[0].ErrorData.ProcedureToTake = "Verifique se o serviço do Processo HFT esta iniciado";
                    _entityMonitor.HFTMonitors[0].ErrorData.Source = "Health Monitor";
                }
            }
            View.CheckErrorList();
        }

        private void TranslateListHftProcessor(List<HFTProcessMonitorEntity> request)
        {
            _hftProcessors.Clear();
            foreach (HFTProcessMonitorEntity item in request)
            {
                Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData itemadd = null;
                if (item != null)
                {
                    itemadd = new Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData();
                    itemadd.Database.LimitOperationAverageTime = item.LimitOperationAverageTime;
                    itemadd.Database.SuccessfulTriesConnection = item.SuccessfulTriesConnection;
                    itemadd.Database.UnsuccessfulTriesConnection = item.UnsuccessfulTriesConnection;
                    itemadd.Database.OperationAverageTime = item.OperationAverageTime;
                    itemadd.MessageProcessor.LastMessageTime = item.LastMessageTimeDate;
                    itemadd.MessageProcessor.LimitWaitingOpenOrderAverageTime = item.LimitWaitingOpenOrderAverageTime;
                    itemadd.MessageProcessor.MessagesPerSecond = item.MessagesPerSecond;
                    itemadd.MessageProcessor.TotalMessages = item.TotalMessages;
                    itemadd.MessageProcessor.WaitingOpenOrderAverageTime = item.WaitingOpenOrderAverageTime;
                    itemadd.Msmq.LimitQueueAcessible = item.MsmqMonitor.LimitQueueAcessible == "Sim" ? true : false;
                    itemadd.Msmq.LimitQueueBytesSize = item.MsmqMonitor.LimitQueueBytesSizeBytes;
                    itemadd.Msmq.LimitQueuedMessages = item.MsmqMonitor.LimitQueuedMessages;
                    itemadd.Msmq.MessagesPerSecond = item.MsmqMonitor.MessagesPerSecond;
                    itemadd.Msmq.QueueAcessible = item.MsmqMonitor.QueueAcessible == "Sim" ? true : false;
                    itemadd.Msmq.QueueBytesSize = item.MsmqMonitor.QueueBytesSizeBytes;
                    itemadd.Msmq.QueuedMessages = item.MsmqMonitor.QueuedMessages;
                    itemadd.Msmq.QueuePath = item.MsmqMonitor.QueuePath;
                    itemadd.ProcessData.HandleCount = item.HandleCount;
                    itemadd.ProcessData.InitializedDate = item.InitializedDate;
                    itemadd.ProcessData.LimitHandleCount = item.LimitHandleCount;
                    itemadd.ProcessData.LimitPrivateMemory = item.LimitPrivateMemoryBytes;
                    itemadd.ProcessData.LimitThreadCount = item.LimitThreadCount;
                    itemadd.ProcessData.MachineIPAddress = item.MachineIPAddress;
                    itemadd.ProcessData.MachineMacAddress = item.MachineMacAddress;
                    itemadd.ProcessData.MachineName = item.MachineName;
                    itemadd.ProcessData.PrivateMemory = item.PrivateMemoryBytes;
                    itemadd.ProcessData.PrivilegedProcessorTime = item.PrivilegedProcessorTimeTimeSpan.ToString();
                    itemadd.ProcessData.ProcessName = item.ProcessName;
                    itemadd.ProcessData.ThreadCount = item.ThreadCount;
                    itemadd.ProcessData.TotalProcessorTime = item.TotalProcessorTime.ToString();
                    itemadd.ProcessData.VirtualMemory = item.HandleCount;
                    itemadd.TotalMsmqConnectionRetries = item.TotalMsmqConnectionRetries;
                    itemadd.ErrorData.BusinessMessage = item.ErrorData.BusinessMessage;
                    itemadd.ErrorData.ErrorCode = item.ErrorData.ErrorCode;
                    itemadd.ErrorData.ErrorDescription = item.ErrorData.ErrorDescription;
                    itemadd.ErrorData.ExceptionMessage = item.ErrorData.ExceptionMessage;
                    itemadd.ErrorData.ProcedureToTake = item.ErrorData.ProcedureToTake;
                    itemadd.ErrorData.Source = item.ErrorData.Source;
                }
                _hftProcessors.Add(itemadd);
            }
        }

        public bool CheckHftProcessOk(Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData request)
        {
            bool ret = true;
            if (request != null)
            {
                if (request.Database.LimitOperationAverageTime < request.Database.OperationAverageTime)
                {
                    ret = false;
                }
                if (request.MessageProcessor.LimitWaitingOpenOrderAverageTime < request.MessageProcessor.WaitingOpenOrderAverageTime)
                {
                    ret = false;
                }
                if (request.Msmq.LimitQueueAcessible != request.Msmq.QueueAcessible)
                {
                    ret = false;
                }
                if (request.Msmq.LimitQueueBytesSize < request.Msmq.QueueBytesSize)
                {
                    ret = false;
                }
                if (request.Msmq.LimitQueuedMessages < request.Msmq.QueuedMessages)
                {
                    ret = false;
                }
                if (request.ProcessData.LimitHandleCount < request.ProcessData.HandleCount)
                {
                    ret = false;
                }
                if (request.ProcessData.LimitPrivateMemory < request.ProcessData.PrivateMemory)
                {
                    ret = false;
                }
                if (request.ProcessData.LimitThreadCount < request.ProcessData.ThreadCount)
                {
                    ret = false;
                }
            }
            else if(NumberOfHftProcessActived != entityMonitor.NumberOfHftProcess)
            {
                ret = false;
            }

            return ret;
        }

        private bool CheckHftProcessesOk(List<Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData> request)
        {
            bool ret;
            if (request.Count > 0)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }
            foreach (Sinacor.OMM.HealthMonitor.Entity.HftProcessor.HftProcessorData item in request)
            {
                ret = ret && CheckHftProcessOk(item);
            }
            return ret;
        }

        public void DisposeHealthMonitorClient()
        {
            if (_healthMonitorClient != null)
                _healthMonitorClient.Dispose();

        }

        private string SizeAdjustmentBytes(long number)
        {
            decimal size;
            string adjustment = string.Empty;
            size = decimal.Parse(number.ToString());

            if (size < KBYTE)
                adjustment = size + " bytes";
            else if (size < MEGABYTE)
                adjustment = Math.Round((size / KBYTE), 2).ToString() + " Kb";
            else if (size < GIGABYTE)
                adjustment = Math.Round((size / MEGABYTE), 2).ToString() + " Mb";
            else
                adjustment = Math.Round((size / GIGABYTE), 2).ToString() + " Gb";
            return adjustment;
        }

        private string SizeAdjustmentBytes(long number, int roundnumber)
        {
            decimal size;
            string adjustment = string.Empty;
            size = decimal.Parse(number.ToString());

            if (size < KBYTE)
                adjustment = size + " bytes";
            else if (size < MEGABYTE)
                adjustment = Math.Round((size / KBYTE), roundnumber).ToString() + " Kb";
            else if (size < GIGABYTE)
                adjustment = Math.Round((size / MEGABYTE), roundnumber).ToString() + " Mb";
            else
                adjustment = Math.Round((size / GIGABYTE), roundnumber).ToString() + " Gb";
            return adjustment;
        }

        private string TimeAdjustment(long number)
        {
            decimal time;
            string adjustment = string.Empty;
            time = decimal.Parse(number.ToString());

            if (time < SECONDS)
            {
                adjustment = time + " ms";
            }
            else if (time < MINUTES)
            {
                adjustment = Math.Round((time / SECONDS), 2).ToString() + " s";
            }
            else if (time < HOURS)
            {
                adjustment = Math.Round((time / MINUTES), 2).ToString() + " min";
            }
            else if (time < DAYS)
            {
                adjustment = Math.Round((time / HOURS), 2).ToString() + " h";
            }
            else
            {
                adjustment = Math.Round((time / DAYS), 2).ToString() + " d";
            }
            return adjustment;
        }

        private string TimeAdjustment(double number)
        {
            decimal time;
            string adjustment = string.Empty;
            time = decimal.Parse(number.ToString());

            if (time < SECONDS)
            {
                adjustment = time + " ms";
            }
            else if (time < MINUTES)
            {
                adjustment = Math.Round((time / SECONDS), 2).ToString() + " s";
            }
            else if (time < HOURS)
            {
                adjustment = Math.Round((time / MINUTES), 2).ToString() + " min";
            }
            else if (time < DAYS)
            {
                adjustment = Math.Round((time / HOURS), 2).ToString() + " h";
            }
            else
            {
                adjustment = Math.Round((time / DAYS), 2).ToString() + " d";
            }
            return adjustment;
        }

        private string TimeSpanAdjustment(TimeSpan time)
        {
            string ret = string.Empty;
            if (time != null)
            {
                ret = time.Hours.ToString().Trim().PadLeft(2, '0') + ":" + time.Minutes.ToString().Trim().PadLeft(2, '0') + ":" + time.Seconds.ToString().Trim().PadLeft(2, '0');
            }
            return ret;
        }

        private string TimeSpanAdjustment(string time)
        {
            string ret = string.Empty;
            TimeSpan timeSpan = TimeSpan.Parse(time);
            if (time != null)
            {
                ret = timeSpan.Hours.ToString().Trim().PadLeft(2, '0') + ":" + timeSpan.Minutes.ToString().Trim().PadLeft(2, '0') + ":" + timeSpan.Seconds.ToString().Trim().PadLeft(2, '0');
            }
            return ret;
        }

        public bool ContainsErrors
        {
            get { return CheckErrors(_entityMonitor.DumperMonitor.ErrorData) || CheckErrors(_entityMonitor.BusinessExecutor.ErrorData) || CheckErrors(_entityMonitor.MatchExecutor.ErrorData) || CheckErrors(_entityMonitor.FinancialExecutor.ErrorData) || CheckErrors(_entityMonitor.OrderExecutor.ErrorData) || CheckErrors(_entityMonitor.ReceptorMonitor.ErrorData) || CheckErrors(_entityMonitor.RouterMonitor.ErrorData) || HftErrors(); }
        }

        public bool CheckErrors(ErrorData errorData)
        {
            return !(String.IsNullOrEmpty(errorData.BusinessMessage) && String.IsNullOrEmpty(errorData.ErrorCode) && String.IsNullOrEmpty(errorData.ErrorDescription) && String.IsNullOrEmpty(errorData.ExceptionMessage) && String.IsNullOrEmpty(errorData.ProcedureToTake) && String.IsNullOrEmpty(errorData.Source));
        }

        public bool HftErrors()
        {
            bool ret = false;
            foreach (HFTProcessMonitorEntity hft in _entityMonitor.HFTMonitors)
            {
                if (hft != null)
                {
                    ret = ret || CheckErrors(hft.ErrorData);
                }
            }
            return ret;
        }

        private string TimeInformationAdjustment(long number)
        {
            decimal time;
            string adjustment = string.Empty;
            time = decimal.Parse(number.ToString());

            if (time < SECONDS)
            {
                adjustment = time + " ms";
            }
            else if (time < MINUTES)
            {
                adjustment = Math.Round((time / SECONDS), 0).ToString() + " s " + Math.Round((time % SECONDS), 2).ToString() + " ms";

            }
            else if (time < HOURS)
            {
                adjustment = Math.Round((time / MINUTES), 2).ToString() + " min";
            }
            else if (time < DAYS)
            {
                adjustment = Math.Round((time / HOURS), 2).ToString() + " h";
            }
            else
            {
                adjustment = Math.Round((time / DAYS), 2).ToString() + " d";
            }
            return adjustment;
        }
    }
}
